
#include <BImage>
#include <BPainter>
#include <BMouseEvent>

#include "PlayYardWidget.h"

PlayYardWidget::PlayYardWidget(BWidget* parent) : BScrollArea(parent)
{
	_dirty = false;
	this->setMargin(20);
	this->setScrollStep(0.1);
	this->setAreaPolicy(Policy_Preferred | Policy_Expanding);
	this->setSpreadSize(100);
	this->setScrollHint(ScrollHint_Floating);
}
PlayYardWidget::~PlayYardWidget()
{

}

bool PlayYardWidget::setAsset(const BValue& asset)
{
	if (this->asset() != asset)
	{
		if (ClassRoom* croom = this->asset())
		{
			disconnect(croom, Signal_Insert);
		}
		BScrollArea::setAsset(asset);
		if (ClassRoom* croom = this->asset())
		{
			connect(croom, Signal_Insert, &PlayYardWidget::slotClassRoomInsert);
		}
		_dirty = true;
		return true;
	}
	return false;
}

const BString& PlayYardWidget::realTips() const
{
	if (_hoveredMate)
	{
		return _hoveredMate->name();
	}
	return BScrollArea::realTips();
}

void PlayYardWidget::slotClassRoomInsert(BObject* object, const BValue& value)
{
	_dirty = true;
	this->fresh();
}

void PlayYardWidget::scrolling(Orientation orientation)
{
	_dirty = true;
	this->fresh();
}

void PlayYardWidget::freshEvent(const BEvent& event)
{
	if (ClassRoom* croom = this->asset())
	{
		if (_dirty)
		{
			int width = 200;
			int height = 0;
			int spacing = 10;
			height = croom->classMateCount() * (100 + spacing);
			this->setAreaSize(width, height);
			const BRect& area = this->area();
			int x = area.x();
			int y = area.y();
			for (int i = 0; i < croom->classMateCount(); i++)
			{
				ClassMate* cmate = croom->classMate(i);
				cmate->setProperty("rect", BRect(x, y, width, 100));
				y += 100 + spacing;
			}
			_dirty = false;
		}
	}
	BScrollArea::freshEvent(event);
}
void PlayYardWidget::paintEvent(const BEvent& event)
{
	BScrollArea::paintEvent(event);
	if (ClassRoom* croom = this->asset())
	{
		BPainter painter(this);
		painter.setClip(this->centerRect());
		for (int i = 0; i < croom->classMateCount(); i++)
		{
			ClassMate* cmate = croom->classMate(i);
			const BRect& rect = cmate->property("rect");
			const BImage* image = cmate->property("image");
			BRect imageRect = rect.align(Align_LeftCenter, 80);
			painter.drawImage(imageRect, image);
			BRect textRect = rect.align(Align_RightCenter, 100);
			painter.setColor(Color_Text);
			painter.drawText(textRect, cmate->name());
		}
	}
}

void PlayYardWidget::mouseMoveEvent(const BMouseEvent& mouseEvent)
{
	if (ClassRoom* croom = this->asset())
	{
		const BPoint& pos = mouseEvent.pos();
		ClassMate* hoveredMate = 0;
		for (int i = 0; i < croom->classMateCount(); i++)
		{
			ClassMate* cmate = croom->classMate(i);
			const BRect& rect = cmate->property("rect");
			if (rect.contain(pos))
			{
				hoveredMate = cmate;
				break;
			}
		}
		if (_hoveredMate != hoveredMate)
		{
			_hoveredMate = hoveredMate;
			this->fresh();
		}
	}
	BScrollArea::mouseMoveEvent(mouseEvent);
}
